package com.derive.education_service.web.agent.sevice.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.derive.education_service.common.global.ResponseMessage;
import com.derive.education_service.entity.Agent;
import com.derive.education_service.entity.User;
import com.derive.education_service.mapper.AgentMapper;
import com.derive.education_service.mapper.UserMapper;
import com.derive.education_service.utils.MyFileUtils;
import com.derive.education_service.web.agent.bean.dto.AgentAddDto;
import com.derive.education_service.web.agent.bean.dto.AgentUpDto;
import com.derive.education_service.web.agent.sevice.AgentService;
import com.vdurmont.emoji.EmojiParser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 代理模式联系方式管理
 */
@Service
@Slf4j
public class AgentServiceImpl implements AgentService {

    @Autowired
    private AgentMapper agentMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private MyFileUtils myFileUtils;

    /**
     * 获取成为管理员和教学点负责人名单 -- 不分页
     * @return
     */
    @Override
    public List<User> getUserAgentBy() {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.ne("user_tag", 2); // 不为普通学员
        List<User> userList = userMapper.selectList(queryWrapper);
        // 转换数据 User的nickName需要表情转码
        userList.stream().forEach(item -> {
            item.setNickName(EmojiParser.parseToUnicode(item.getNickName()));
        });
        return userList;
    }

    /**
     * 添加负责人/代理联系方式 -- 唯一(需要检验是否已存在记录)
     * @param file
     * @param agentAddDto
     * @return
     */
    @Override
    public ResponseMessage addAgent(MultipartFile file, AgentAddDto agentAddDto) {
        // 验证是否存在记录
        QueryWrapper<Agent> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("open_id", agentAddDto.getOpenId());
        Agent agent = agentMapper.selectOne(queryWrapper);
        if (agent != null) {
            // 已经存在记录
            return ResponseMessage.createByErrorMessage("该用户已存在记录");
        }
        // 添加新的记录
        Agent a = new Agent();
        BeanUtils.copyProperties(agentAddDto, a);
        // 上传微信二维码
        try {
            ResponseMessage r = myFileUtils.uploadFile(file, "agent");
            if (r.getStatus() == 1) {
                return r;
            }
            a.setErUrl(String.valueOf(r.getData())); // 填充资源地址
        } catch (IOException e) {
            e.printStackTrace();
            log.error("代理微信二维码上传失败");
            return ResponseMessage.createByErrorMessage("代理微信二维码上传失败");
        }
        a.setCreateTime(new Date());
        a.setUpdateTime(new Date());
        int row = agentMapper.insert(a);
        if (row <= 0) {
            return ResponseMessage.createByErrorMessage("新增异常");
        }
        return ResponseMessage.createBySuccessMessage("新增代理成功");
    }

    /**
     * 删除负责人联系方式
     * @param agentId
     * @return
     */
    @Override
    public ResponseMessage delAgent(int agentId) {
        // 先删除资源
        String erUrl = agentMapper.selectById(agentId).getErUrl();
        ResponseMessage r = myFileUtils.delFile(erUrl);
        if (r.getStatus() == 1) {
            return r;
        }
        // 直接删除就好了
        int row = agentMapper.deleteById(agentId);
        if (row <= 0) {
            return ResponseMessage.createByErrorMessage("删除异常");
        }
        return ResponseMessage.createBySuccessMessage("删除成功");
    }

    /**
     * 编辑代理联系方式信息
     * @param file
     * @param agentUpDto
     * @return
     */
    @Override
    public ResponseMessage upAgent(MultipartFile file, AgentUpDto agentUpDto) {
        String s = "";
        // 判断是否需要更新文件
        if (file != null && !file.isEmpty()) {
            // 有传文件，所以认为是更新了文件，先删除
            String erUrl = agentMapper.selectById(agentUpDto.getAgentId()).getErUrl();
            if (myFileUtils.delFile(erUrl).getStatus() == 1) {
                return ResponseMessage.createByErrorMessage("删除文件异常");
            }
            // 上传文件
            try {
                ResponseMessage r = myFileUtils.uploadFile(file, "agent");
                if (r.getStatus() == 1) {
                    return r;
                }
                s = String.valueOf(r.getData());
            } catch (IOException e) {
                e.printStackTrace();
                log.error("文件更新异常");
                return ResponseMessage.createByErrorMessage("文件更新异常");
            }
        }
        // 数据填充
        Agent agent = new Agent();
        BeanUtils.copyProperties(agentUpDto, agent);
        agent.setErUrl(s);
        agent.setUpdateTime(new Date());

        int row = agentMapper.updateById(agent);
        if (row <= 0) {
            return ResponseMessage.createByErrorMessage("更新异常");
        }
        return ResponseMessage.createBySuccessMessage("更新成功");
    }

    /**
     * 查看代理联系详情信息
     * @param openId
     * @return
     */
    @Override
    public ResponseMessage getAgentByOpenId(String openId) {
        QueryWrapper<Agent> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("open_id", openId);
        Agent agent = agentMapper.selectOne(queryWrapper);

        if (agent == null) {
            return ResponseMessage.createByErrorMessage("代理不存在");
        }
        return ResponseMessage.createBySuccess(agent);
    }
}
